package org.example.execute;

import cn.hutool.core.util.StrUtil;
import org.apache.maven.plugin.logging.Log;
import org.example.dto.ColumnDto;
import org.example.service.GenerateCode;
import org.example.utils.HumpUtils;

import java.util.List;
import java.util.Properties;

public class MapperXml implements GenerateCode {

    public void execute(Log log,  String entity, String content, Properties properties) {
        String className = HumpUtils.className(StrUtil.format("{}_mapper", entity));
        StringBuffer buffer = new StringBuffer();
        try {
            String entityPath = StrUtil.format("{}.{}", properties.getProperty("generator.entity.path"), HumpUtils.className(StrUtil.format("{}_entity", entity)));
            String mapperPath = StrUtil.format("{}.{}", properties.getProperty("generator.mapper.path"), className);
            String path = StrUtil.format("src/main/resources/mapper/{}.xml", className);
            this.createFile(log, path);
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            buffer.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
            buffer.append(StrUtil.format("<mapper namespace=\"{}\">\n", mapperPath));
            buffer.append(StrUtil.format("\t<resultMap id=\"BaseResultMap\" type=\"{}\">\n", entityPath));
            buffer.append(content);
            buffer.append("\t</resultMap>\n\n");
            buffer.append("</mapper>");
            writeContent(log, path, buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execute(Log log, String entity, List<ColumnDto> columnDtoList, Properties properties) {
        Boolean service = Boolean.parseBoolean(properties.getProperty("generator.mapper"));
        if (service) {
            StringBuffer buffer = new StringBuffer();
            columnDtoList.stream().forEach(columnDto -> {
                if (columnDto.getField().equals("id")) {
                    buffer.append(StrUtil.format("\t\t<id column=\"{}\" jdbcType=\"{}\" property=\"{}\" />\n", columnDto.getField(), getXMLType(columnDto.getType()), HumpUtils.fieldName(columnDto.getField())));
                } else {
                    buffer.append(StrUtil.format("\t\t<result column=\"{}\" jdbcType=\"{}\" property=\"{}\" />\n", columnDto.getField(), getXMLType(columnDto.getType()), HumpUtils.fieldName(columnDto.getField())));
                }
            });
            log.info(entity + "service 生成");
            execute(log, entity, buffer.toString(), properties);
        }
    }

    private Object getXMLType(String type) {
        if (type.contains("int")) {
            return "BIGINT";
        }
        return "VARCHAR";
    }
}
